package com.coderman.api.system.controller;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.coderman.api.biz.enums.FaceConstant;
import com.coderman.api.biz.enums.ImageTypeEnum;
import com.coderman.api.biz.enums.LivenessControlEnum;
import com.coderman.api.biz.enums.QualityControlEnum;
import com.coderman.api.common.bean.ResponseBean;
import com.coderman.api.common.utils.ImageU;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.HashMap;

@Api(tags = "人脸识别")
@RestController
@RequestMapping("/face")
public class FaceController {
    private static final String APP_ID = "26019897";
    private static final String APP_KEY = "4nq3qgKXvWbqVesoi4CKcO5f";
    private static final String SECRET_KEY = "O1Oof5PiqdfevFCzfwZhZmyqlcRZnIHq";
    private static volatile AipFace client = new AipFace(APP_ID, APP_KEY, SECRET_KEY);

    /**
     * 人脸识别接口
     *
     * @return  ResponseBean
     */
    @ApiOperation(value = "人脸识别", notes = "人脸识别,根据拍照搜索人脸库")
    @RequestMapping("/search")
    public ResponseBean   face(@RequestBody String   img) throws IOException {
        String  groupIds="gropu001";
//        System.out.println(img);
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(img);
        String  data=jsonObject.getString("img");
        data=data.substring(data.indexOf(",")+1);
        ImageU imageU = ImageU.builder().data(data).imageTypeEnum(ImageTypeEnum.BASE64).build();
        boolean result = faceSearch(groupIds, imageU);

        System.out.println(result);

        if(result){
            return ResponseBean.success("人脸识别成功！");
        }else{
            return ResponseBean.error("人脸识别失败！");
        }
    }

    /**
     * 人脸搜索
     */
    public static boolean faceSearch(String groupIds, ImageU imageU) {
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("max_face_num", "1");
        options.put("max_user_num", "1");
        options.put("quality_control", QualityControlEnum.LOW.name());
        options.put("liveness_control", LivenessControlEnum.NONE.name());
        // 人脸搜索
        JSONObject res = client.search(imageU.getData(), imageU.getImageTypeEnum().name(), groupIds, options);
        System.out.println("结果："+res);

        boolean   flag=false;
        int errorCode = res.has(FaceConstant.ERROR_CODE) ? res.getInt(FaceConstant.ERROR_CODE) : -1;

        if(errorCode==0){
            if(res.getJSONObject("result").getJSONArray("user_list").getJSONObject(0).getDouble("score")>=80)
            {
                flag=true;
            }
        }
        return flag;
    }

    /**
     * 编码
     * @param form
     * @return
     */
    public static String  encodeBase64(byte[] form){
        return Base64Util.encode(form);
    }

    /**
     * 解码
     * @param data
     * @return
     */
    public static byte[] decodeBase64(String data){
        return Base64Util.decode(data);
    }



//    public static String imageToBase64(String imgPath){
//        InputStream inputStream = null;
//        byte[] data = null;
//        try {
//            inputStream = new FileInputStream(imgPath);
//            data = new byte[inputStream.available()];
//            inputStream.read(data);
//            inputStream.close();
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//        BASE64Encoder encoder = new BASE64Encoder();
//        //返回编码完成的base64图像数据
//        return encoder.encode(data);
//    }

//    public static void main(String[] args) {
//        String   filePath="C:\\Users\\ASUS\\Desktop\\000000.jpg";
//
//        String  groupIds="gropu001";
//        String  data=imageToBase64(filePath);
//        ImageU imageU = ImageU.builder().data(data).imageTypeEnum(ImageTypeEnum.BASE64).build();
//        boolean result = faceSearch(groupIds, imageU);
//
//        System.out.println(result);
//    }


}
